package com.kin.rich.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * A data access object (DAO) providing persistence and search support for
 * Company entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.kin.rich.pojo.Company
 * @author MyEclipse Persistence Tools
 */

public class CommonDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(CommonDAO.class);
	// property constants

	protected void initDao() {
		// do nothing
	}
	
	public static void main(String[] args){
		ApplicationContext appContext = new FileSystemXmlApplicationContext("/src/applicationContext.xml");
		CommonDAO dao =  CommonDAO.getFromApplicationContext(appContext);
		String today = "2010-01-01";
		String countHql = "select searchTimes from Searchdata where wordId="+1+" and searchDate='"+today+"' and source='BaiduWeb' and searchTimes>0";
		System.out.println(dao.count(countHql));
	}

	public List findByQuery(final String hql,final int first,final int offset){
		try{
			return this.getHibernateTemplate().executeFind(new HibernateCallback(){
				public Object doInHibernate(Session session) throws HibernateException ,SQLException{
					Query query = session.createQuery(hql);
					query.setFirstResult(first);
					if(offset > 0)
						query.setMaxResults(offset);
					return query.list();
				}
			});
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	public int count(String hql){
		try{
			List list = getHibernateTemplate().find(hql);
			if(list != null && list.size()>0){
				String string = list.get(0).toString();
				if(string != null)
					return Integer.parseInt(string);
			}
			return 0;
			//return list == null || list.size() == 0 ? 0 : ((Integer)list.listIterator().next()).intValue();
			//return ((Integer)getHibernateTemplate().find(hql).listIterator().next()).intValue();
		}catch(Exception e){
			e.printStackTrace();
			return 0;
		}		
	}
	
	public static CommonDAO getFromApplicationContext(ApplicationContext ctx) {
		return (CommonDAO) ctx.getBean("CommonDAO");
	}
}